package com.banciyuan.bcywebview.biz.privatemessage;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.MessageApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.dialog.ChooseDialog;
import com.banciyuan.bcywebview.base.view.dialog.ConfirmDialog;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.report.UserReportActivity;
import com.banciyuan.bcywebview.biz.share.ShareActivity;
import com.banciyuan.bcywebview.biz.share.block.BlockHelper;
import com.banciyuan.bcywebview.biz.share.block.IBlockHelper;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.PrivateMessage;
import de.greenrobot.daoexample.model.User;
import de.greenrobot.daoexample.model.UserDetail;

/**
 * Created by squall on 2016/9/9.
 */
public class PrivateMessageActivity extends BaseActivity {

    private PullToRefreshListView mRefresh;
    private ListView mListView;
    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;
    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private RequestQueue queue;

    private List<PrivateMessage> plist = new ArrayList<>();
    private PrivateMessageAdapter privateMessageAdapter;
    private PrivateMessage message;
    private int page = 1;
    private boolean is_end;
    private final static int GO_REPLY = 1024;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_private_message);
        initArgs();
        initActionbar();
        initProgressbar();
        initUi();
        initData();
        initAction();
    }

    @Override
    protected void initArgs() {
        queue = VolleyQueue.getRquest(this);
        message = (PrivateMessage) getIntent().getSerializableExtra(gotoUtil.INTENT_VALUE_ONE);
    }

    @Override
    protected void initUi() {
        mRefresh = (PullToRefreshListView) findViewById(R.id.topic_refresh_lv);
        mListView = mRefresh.getRefreshableView();
    }

    @Override
    protected void initAction() {
        mRefresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (!is_end) {
                    page++;
                    initData();
                } else {
                    MyToast.show(PrivateMessageActivity.this, getString(R.string.reach_the_top));
                    mRefresh.post(new Runnable() {
                        @Override
                        public void run() {
                            mRefresh.onRefreshComplete();
                        }
                    });
                }
            }
        });
        findViewById(R.id.rl_publish).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PrivateMessageActivity.this, EditPrivateMessageActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, message);
                intent.putExtra(gotoUtil.INTENT_VALUE_TWO, "reply");
                startActivityForResult(intent, GO_REPLY);
                overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
            }
        });

        findViewById(R.id.base_action_bar_itemone).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = message.getUname();
                if (!TextUtils.isEmpty(name)) {
                    if (name.length() > 7) {
                        name = name.substring(0, 7) + "...";
                    }
                }
                ChooseDialog.Builder builder = new ChooseDialog.Builder(PrivateMessageActivity.this);
                builder.setChooseOneString(String.format(getString(R.string.block_list_in), name))
                        .setChooseOneClick(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                User user = new User();
                                user.setUid(message.getUid());
                                user.setUname(message.getUname());

                                block(user, new IBlockHelper() {
                                    @Override
                                    public void getSucc(String json) {
                                        MyToast.show(PrivateMessageActivity.this, getString(R.string.block_succ));
                                    }

                                    @Override
                                    public void getFail() {

                                    }
                                });
                            }
                        })
                        .setChooseTwoString(String.format(getString(R.string.report_unit), name))
                        .setChooseTwoClick(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                UserDetail user = new UserDetail();
                                user.setUid(message.getUid());
                                user.setUname(message.getUname());

                                Intent intent = new Intent(PrivateMessageActivity.this, UserReportActivity.class);
                                intent.putExtra("user", user);
                                startActivity(intent);
                            }
                        })
                        .create().show();
            }
        });

    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + MessageApi.getMessageMsgDetail();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        pairs.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        pairs.add(new BcyPair("message_id", message.getSource_message_id()));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, PrivateMessageActivity.this)) {
                        JSONObject jsonObject = new JSONObject(response);
                        Gson gson = new Gson();
                        List<PrivateMessage> templist =
                                gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<PrivateMessage>>() {
                                }.getType());
                        renderData(templist);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, PrivateMessageActivity.this, map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        queue.add(requestParam);
    }

    private void renderData(List<PrivateMessage> templist) {
        if (templist.isEmpty()) {
            is_end = true;
        }
        plist.addAll(templist);
        if (privateMessageAdapter == null) {
            privateMessageAdapter = new PrivateMessageAdapter(plist, this);
            mListView.setAdapter(privateMessageAdapter);
        } else {
            privateMessageAdapter.notifyDataSetChanged();
        }
        if (page == 1) {
            mListView.setSelection(plist.size());
        }
        mRefresh.onRefreshComplete();
        mProgressbarHelper.onSuccess();
    }

    private void showReply(PrivateMessage privateMessage) {
        plist.add(0, privateMessage);
        if (privateMessageAdapter == null) {
            privateMessageAdapter = new PrivateMessageAdapter(plist, this);
            mListView.setAdapter(privateMessageAdapter);
        } else {
            privateMessageAdapter.notifyDataSetChanged();
        }
        mListView.setSelection(plist.size());
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(message.getUname());
        mActionbarHelper.addOneAction(R.drawable.more_black);
    }

    private void block(final User user, IBlockHelper iBlockHelper) {
        if (user == null) return;
        final BlockHelper blockHelper = new BlockHelper(iBlockHelper, PrivateMessageActivity.this);
        View.OnClickListener comfirmAction = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                blockHelper.doBlock(UserDataHelper.getInstance(PrivateMessageActivity.this).getToken(), user.getUid());
            }
        };
        ConfirmDialog.Builder builder = new ConfirmDialog.Builder(this);
        builder.setDescString(getString(R.string.enter_block_list))
                .setActionString(getString(R.string.comfirm_to_block_list))
                .setCancelString(getString(R.string.mydialog_cancel))
                .setActionClickListener(comfirmAction).create().show();
        setResult(ShareActivity.BLOCK);
    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GO_REPLY && resultCode == RESULT_OK) {
            if (data != null) {
                showReply((PrivateMessage) data.getSerializableExtra("privatemessage"));
            }
        }
    }
}
